<template>
  <div class="forum-container">
    <NavigationBar />
    <div class="forum-content">
      <h1 class="forum-title">宠物交流论坛</h1>
      <p class="forum-subtitle">分享您的宠物故事和经验</p>

      <button @click="openNewPostDialog" class="new-post-button">
        <i class="fas fa-plus"></i> 发表新帖
      </button>

      <div class="forum-list">
        <div v-for="post in posts" :key="post.id" class="forum-post" @click="viewPost(post.id)">
          <div class="post-header">
            <h2 class="post-title">{{ post.title }}</h2>
            <span class="post-date">{{ formatDate(post.date) }}</span>
          </div>
          <p class="post-excerpt">{{ truncateContent(post.content) }}</p>
          <div class="post-footer">
            <span class="post-author">
              <i class="fas fa-user"></i> {{ post.author }}
            </span>
            <span class="post-comments">
              <i class="fas fa-comment"></i> {{ post.comments }} 条评论
            </span>
            <span class="post-likes">
              <i class="fas fa-heart"></i> {{ post.likes }} 点赞
            </span>
          </div>
        </div>
      </div>
    </div>

    <!-- 发帖对话框 -->
    <div v-if="showNewPostDialog" class="dialog-overlay">
      <div class="new-post-dialog">
        <h3>发表新帖</h3>
        <form @submit.prevent="submitNewPost">
          <div class="form-group">
            <label for="post-title">标题</label>
            <input v-model="newPost.title" type="text" id="post-title" placeholder="输入帖子标题" required>
          </div>
          <div class="form-group">
            <label for="post-content">内容</label>
            <textarea v-model="newPost.content" id="post-content" placeholder="输入帖子内容" rows="6" required></textarea>
          </div>
          <div class="dialog-buttons">
            <button type="button" @click="closeNewPostDialog" class="cancel-button">
              取消
            </button>
            <button type="submit" class="submit-button">
              发布
            </button>
          </div>
        </form>
      </div>
    </div>

    <Footer />
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import NavigationBar from '@/components/NavigationBar.vue'
import Footer from '@/components/Footer.vue'

const router = useRouter()
const posts = ref([])

// 获取帖子列表
const fetchPosts = async () => {
  try {
    const response = await fetch('http://localhost:3000/posts')
    if (!response.ok) throw new Error('获取帖子失败')
    posts.value = await response.json()
  } catch (error) {
    console.error('获取帖子失败:', error)
  }
}

onMounted(() => {
  fetchPosts()
})

// 新帖子相关状态
const showNewPostDialog = ref(false)
const newPost = ref({
  title: '',
  content: ''
})

// 打开帖子详情
const viewPost = (postId) => {
  router.push({ name: 'PostDetail', params: { postId } })
}

// 打开发帖对话框
const openNewPostDialog = () => {
  showNewPostDialog.value = true
}

// 关闭发帖对话框
const closeNewPostDialog = () => {
  showNewPostDialog.value = false
  newPost.value = { title: '', content: '' }
}

// 提交新帖子
const submitNewPost = async () => {
  try {
    const token = localStorage.getItem('token')
    if (!token) {
      router.push('/')
      return
    }

    const response = await fetch('http://localhost:3000/posts', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': token
      },
      body: JSON.stringify(newPost.value)
    })

    if (!response.ok) throw new Error('发布帖子失败')

    // 刷新帖子列表
    await fetchPosts()
    closeNewPostDialog()
  } catch (error) {
    console.error('发布帖子失败:', error)
    alert('发布帖子失败，请重试')
  }
}

// 格式化日期
const formatDate = (dateString) => {
  const date = new Date(dateString)
  return date.toLocaleDateString() + ' ' + date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })
}

// 截断内容预览
const truncateContent = (content) => {
  return content.length > 100 ? content.substring(0, 100) + '...' : content
}
</script>
<style scoped>
.forum-container {
  background-color: #fffaf5;
  min-height: 100vh;
}

.forum-content {
  max-width: 1200px;
  margin: 0 auto;
  padding: 2rem 1.5rem;
}

.forum-title {
  color: #8b7355;
  font-size: 2.4rem;
  font-weight: bold;
  text-align: center;
  margin-bottom: 0.5rem;
  /* font-weight: 500; */
}

.forum-subtitle {
  color: #7f6b5e;
  text-align: center;
  margin-bottom: 2rem;
  font-size: 1.1rem;
}

.new-post-button {
  background: #f5e6d3;
  color: #6d4c3d;
  border: none;
  border-radius: 25px;
  padding: 0.8rem 2rem;
  font-size: 1rem;
  cursor: pointer;
  transition: all 0.3s ease;
  margin-bottom: 2rem;
  display: flex;
  align-items: center;
  gap: 0.8rem;
  box-shadow: 0 2px 8px rgba(0,0,0,0.05);
}

.new-post-button:hover {
  background: #e8d5c4;
  transform: translateY(-2px);
}

.forum-list {
  display: grid;
  gap: 1.5rem;
}

.forum-post {
  background: white;
  border-radius: 12px;
  padding: 1.5rem;
  cursor: pointer;
  transition: all 0.2s ease;
  box-shadow: 0 3px 6px rgba(0,0,0,0.04);
  border: 1px solid #f0e2d4;
}

.forum-post:hover {
  transform: translateY(-3px);
  box-shadow: 0 5px 15px rgba(0,0,0,0.08);
}

.post-header {
  display: flex;
  justify-content: space-between;
  align-items: baseline;
  margin-bottom: 1rem;
}

.post-title {
  color: #5a4132;
  font-size: 1.3rem;
  margin: 0;
  flex: 1;
}

.post-date {
  color: #9c8a7d;
  font-size: 0.9rem;
  margin-left: 1.5rem;
}

.post-excerpt {
  color: #635347;
  line-height: 1.7;
  margin-bottom: 1.2rem;
  font-size: 0.95rem;
}

.post-footer {
  display: flex;
  gap: 1.5rem;
  color: #8c7465;
  font-size: 0.9rem;
}

.post-footer i {
  color: #d4a88c;
  margin-right: 0.3rem;
}

/* 发帖对话框样式 */
.dialog-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0,0,0,0.2);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.new-post-dialog {
  background: white;
  border-radius: 15px;
  padding: 2rem;
  width: 600px;
  box-shadow: 0 8px 20px rgba(0,0,0,0.1);
}

.new-post-dialog h3 {
  color: #5a4132;
  margin-bottom: 1.5rem;
  font-size: 1.5rem;
}

.form-group {
  margin-bottom: 1.5rem;
}

.form-group label {
  display: block;
  color: #7f6b5e;
  margin-bottom: 0.5rem;
  font-weight: 500;
}

input, textarea {
  width: 100%;
  padding: 0.8rem;
  border: 2px solid #f0e2d4;
  border-radius: 8px;
  font-size: 1rem;
  transition: border-color 0.3s ease;
}

input:focus, textarea:focus {
  outline: none;
  border-color: #d4a88c;
}

textarea {
  resize: vertical;
  min-height: 120px;
}

.dialog-buttons {
  display: flex;
  gap: 1rem;
  justify-content: flex-end;
  margin-top: 2rem;
}

.submit-button, .cancel-button {
  padding: 0.8rem 1.5rem;
  border-radius: 8px;
  font-weight: 500;
  transition: all 0.3s ease;
}

.submit-button {
  background: #f5e6d3;
  color: #6d4c3d;
  border: none;
}

.submit-button:hover {
  background: #e8d5c4;
}

.cancel-button {
  background: transparent;
  color: #8c7465;
  border: 2px solid #f0e2d4;
}

@media (max-width: 768px) {
  .forum-content {
    padding: 1rem;
  }

  .forum-title {
    font-size: 1.8rem;
  }

  .new-post-dialog {
    width: 90%;
    padding: 1.5rem;
  }

  .forum-post {
    padding: 1rem;
  }

  .post-header {
    flex-direction: column;
    gap: 0.5rem;
  }

  .post-date {
    margin-left: 0;
  }
}
</style>
